package net.wang.zk.curator.test;


import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class ZKCuratorExample {

    public static final String zkConnectString = "127.0.0.1:2181";

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    @Test
    public void testConnect() throws InterruptedException {


        /**连接重试机制*/
        //间隔时间、最大用时，重试最大次数 推荐
//        RetryPolicy retryPolicy = new BoundedExponentialBackoffRetry(5000, 15000, 3);
        //重试三次，间隔时间5秒  推荐
//        RetryPolicy retryPolicy = new RetryNTimes(3, 500);
        //一直重试，间隔时间5秒
//        RetryPolicy retryPolicy = new RetryForever(5000);
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(5000, 15000, 3);
        /**原生API连接过程是异步的，Curator同步*/
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zkConnectString).connectionTimeoutMs(5000).retryPolicy(retryPolicy).namespace("testNameSpace").build();
        client.start();
        log.info("===>state : {}", client.getState());
        Thread.sleep(3000);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(() -> {
            if (client.isStarted()) {
                client.close();
            }
            countDownLatch.countDown();
        });
        countDownLatch.await();

    }
}
